import { createDefaultOptionsFactory } from "./configs/vmi-base.config";
import { start } from "./orders";
import {
  PROCESS_ENV_TYPES,
  PROCESS_ENV_TYPE_VALUES,
  setEnv,
  isObject,
  mergeVmiServerOptions,
  TEAMPLTE_PATH,
  RUN_TEMPLATE_PATH,
  logger
} from "./uitls";

import type { CONFIG, SERVER_CONFIG } from '../types/config'
import type { DeepRequired } from "../types";
import Event from 'events'
import { generatorTemplate } from './uitls';
import fs from 'fs-extra'
import path from "path";

class VMI extends Event {
  private options: DeepRequired<CONFIG>;
  private finishGeneratorTemplate: boolean = false
  constructor() {
    super()
    this.options = createDefaultOptionsFactory();
    this.init()
  }

  private init () {
    try {
      this.checkDir()
      this.initTemplate()
    } catch (error) {
      logger.error(error as string)
    }
  }

  private checkDir () {
    logger.success('检测文件...')
    const { root, componentRoot } = this.options
    const componentRootPath = path.join(root, componentRoot)
    const isExistComponentDir = fs.existsSync(componentRootPath)
    if (!isExistComponentDir) {
      throw Error('components文件夹不存在，请创建后在启动')
    }
  }

  private initTemplate () {
    logger.success('生成模板中...')
    generatorTemplate(TEAMPLTE_PATH, RUN_TEMPLATE_PATH, this.options)
    this.finishGeneratorTemplate = true
    this.emit('finishGeneratorTemplate')
    logger.success('生成模板成功...')
  }

  start(serverOption?: SERVER_CONFIG) {
    if (!this.finishGeneratorTemplate) {
      return this.once('finishGeneratorTemplate', this.start)
    }
    logger.success('正在启动服务...')
    setEnv(PROCESS_ENV_TYPES.NODE_ENV, PROCESS_ENV_TYPE_VALUES.DEVELOPMENT);
    if (isObject(serverOption)) {
      this.options.devServer = mergeVmiServerOptions(this.options.devServer, serverOption);
    }
    start(this.options);
  }
}

export default VMI;
